self.onmessage = (event) => {
    const { type, key, data, debounce = 300 } = event.data || {};
    switch (type) {
        case 'schedule': {
            schedulePersist(key, data, debounce);
            break;
        }
        case 'flush': {
            flushPersist();
            break;
        }
        case 'cancel': {
            cancelPersist();
            break;
        }
        default:
            break;
    }
};

let pendingTimer = null;
let latestJob = null;

const schedulePersist = (key, data, debounce) => {
    if (!key) return;
    latestJob = { key, data };
    if (pendingTimer) {
        clearTimeout(pendingTimer);
    }
    pendingTimer = setTimeout(() => {
        pendingTimer = null;
        flushPersist();
    }, typeof debounce === 'number' ? debounce : 300);
};

const flushPersist = () => {
    if (!latestJob) return;
    const { key, data } = latestJob;
    latestJob = null;
    try {
        const serialized = JSON.stringify(data ?? {});
        self.postMessage({
            type: 'persist',
            key,
            serialized
        });
    } catch (error) {
        self.postMessage({
            type: 'error',
            key,
            message: error?.message || 'Failed to serialize state'
        });
    }
};

const cancelPersist = () => {
    if (pendingTimer) {
        clearTimeout(pendingTimer);
        pendingTimer = null;
    }
    latestJob = null;
};
